//
//  MYGFindSendController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/19.
//

import UIKit
import QMUIKit
import DGCollectionViewLeftAlignFlowLayout
import TZImagePickerController

class MYGFindSendController: MYGBaseController {
    
    var isShowImageView:Bool = true
    var videos: PHAsset?
    private var contents: [MYGFindSendImageCellModel] = []
    private var images: [UIImage] = []
    private var poition: CLLocationCoordinate2D?
    
    private var statusModel: MYGWhoSeeModel? {
        didSet {
            let model = statusModel ?? MYGWhoSeeModel()
            statusView.hintLabel.text = model.showText
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        if isShowImageView{configCell()}
        
        MYGPositionManager.shared.startLocation { coor, city in
            if self.poition == nil {
                self.poition = coor
                self.positionView.hintLabel.text = city
            }
        }
    }
    
    // MARK: - Cell
    private func configCell() {
        contents = []
        
        for image in images {
            let model = MYGFindSendImageCellModel()
            model.image = image
            model.removeAction = {[weak self] in
                self?.images.removeAll(image)
                if self?.videos != nil {
                    self?.videos = nil
                }
                self?.configCell()
            }
            contents.append(model)
        }
        
        if contents.count < 9 && videos == nil {
            let model = MYGFindSendImageCellModel()
            model.isAdd = true
            contents.append(model)
        }
        
        collectionView.reloadData()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "发表动态"
        
        view.backgroundColor = .white
        
        view.addSubview(scrollView)
        view.addSubview(cancelButton)
        view.addSubview(sendButton)
        scrollView.addSubview(mainView)
        mainView.addSubview(textView)
        mainView.addSubview(collectionView)
        mainView.addSubview(positionView)
        mainView.addSubview(statusView)
        
        scrollView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(cancelButton.snp.top)
        }
        
        mainView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(screenWidth)
        }
        
        textView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.top.equalToSuperview().offset(15)
            make.height.equalTo(63)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.top.equalTo(textView.snp.bottom).offset(5)
            make.height.equalTo(96)
        }
        
        positionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(61)
            make.height.equalTo(46)
        }
        
        statusView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(positionView.snp.bottom).offset(0)
            make.height.equalTo(46)
            make.bottom.equalToSuperview().inset(10)
        }
        
        cancelButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(22)
            make.bottom.equalToSuperview().inset(19+bottomSafeheight)
            make.width.equalTo((screenWidth-74)/2)
            make.height.equalTo(32)
        }
        
        sendButton.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(22)
            make.bottom.equalToSuperview().inset(19+bottomSafeheight)
            make.width.equalTo((screenWidth-74)/2)
            make.height.equalTo(32)
        }
    }
    

    // MARK: - lazy load
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .white
        return scrollView
    }()
    
    private lazy var mainView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var textView: QMUITextView = {
        let tv = QMUITextView()
        tv.placeholder = "这一刻的想法…"
        tv.placeholderColor = .rgba(148, 148, 148, 1)
        
        tv.font = .regular(18)
        tv.textColor = .rgba(51, 51, 51)
        return tv
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = DGCollectionViewLeftAlignFlowLayout()
        layout.itemSize = CGSize(width: 96, height: 96)
        layout.minimumLineSpacing = 14
        layout.minimumInteritemSpacing = 14
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: MYGFindSendImageCell.self)
        cv.addObserver(self, forKeyPath: "contentSize", context: nil)
        return cv
    }()
    
    private lazy var positionView: MYGFindSendMessageView = {
        let view = MYGFindSendMessageView()
        view.imageView.image = UIImage(named: "Find/position")
        view.nameLabel.text = "所在位置"
        view.hintLabel.text = ""
        view.topLineView.isHidden = false
        view.bottomLineView.isHidden = true
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(clickView))
        view.isUserInteractionEnabled = true
        view.addGestureRecognizer(tap)
        return view
    }()
    
    private lazy var statusView: MYGFindSendMessageView = {
        let view = MYGFindSendMessageView()
        view.imageView.image = UIImage(named: "Find/man")
        view.nameLabel.text = "谁可以看"
        view.hintLabel.text = "公开"
        view.topLineView.isHidden = false
        view.bottomLineView.isHidden = false
        let tap = UITapGestureRecognizer(target: self, action: #selector(clickView))
        view.isUserInteractionEnabled = true
        view.addGestureRecognizer(tap)
        return view
    }()
    
    private lazy var cancelButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消", for: .normal)
        btn.setTitleColor(.rgba(116, 116, 116, 1), for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 16
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor.rgba(197, 197, 197, 1).cgColor
        
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
    private lazy var sendButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("发表", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .medium(14)
        //btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 16
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        return btn
    }()
    
    @objc
    private func clickView(_ tap: UITapGestureRecognizer) {
        if tap.view == positionView {
            let vc = YMCitySelect(delegate: self)!
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        } else if tap.view == statusView {
            let vc = MYGWhoSeeController()
            vc.selectAction = {[weak self] model in
                self?.statusModel = model
            }
            vc.show()
        }
    }
    
    @objc
    private func clickButton(_ btn: UIButton) {
        if btn == cancelButton {
            self.navigationController?.popViewController()
        } else if btn == sendButton {
            sendMessage()
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let keyPath = keyPath, keyPath == "contentSize" {
            collectionView.snp.remakeConstraints { make in
                make.left.right.equalToSuperview().inset(20)
                make.top.equalTo(textView.snp.bottom).offset(5)
                make.height.equalTo(collectionView.contentSize.height)
            }
        }
    }
}

extension MYGFindSendController: YMCitySelectDelegate {
    func ym_ymCitySelectCityName(_ cityName: String!) {
        positionView.hintLabel.text = cityName
    }
}

extension MYGFindSendController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: MYGFindSendImageCell.self, for: indexPath)
       
        cell.model = contents[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = contents[indexPath.row]
        if model.isAdd {
            let pick = TZImagePickerController(maxImagesCount: 9-contents.count, delegate: self)
            pick?.maxImagesCount = 9-contents.count
            if images.count > 0 {
                pick?.allowTakeVideo = false
                pick?.allowPickingVideo = false
            } else {
                pick?.allowTakeVideo = true
                pick?.allowPickingVideo = true
            }

            self.present(pick!, animated: false)
        }
    }
}

extension MYGFindSendController: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        self.images.append(contentsOf: photos)
        configCell()
    }
    
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: PHAsset!) {
        self.images.append(coverImage)
        self.videos = asset
        configCell()
    }
    
    private func sendMessage() {
        guard let text = textView.text, !text.isEmpty else {
            MMYGHUD.showToast(text: "请输入动态内容")
            return
        }
        
        if isShowImageView == true {
            guard images.count > 0 else {
                MMYGHUD.showToast(text: "请选择图片")
                return
            }
            
        }
      
        let address = positionView.hintLabel.text ?? ""
        let lng = poition?.longitude ?? 0
        let lat = poition?.latitude ?? 0
        
        let range = statusModel?.value ?? 0
        
        let group = DispatchGroup()
        var urls: [String] = []
        var error: String?
        MYGLoading.show()
        if let videos = videos {
//            let asset = TZImageManager.
            group.enter()
            TZImageManager().requestVideoURL(with: videos) { url in
                guard let url = url, let data = try? Data(contentsOf: url) else {
                    return
                }
                
                MMYGNetwork<MYGCommonAPI, MYGEmptyModel>.request(target: .uploadOssFiles(image: nil, data: data, fileName: "\(Int(Date().timeIntervalSince1970)).mp4", type: "audio/*")) { _ in
                    
                } stringBlock: { text in
                    urls.append(text)
                    group.leave()
                } failed: { _, err in
                    error = err
                    group.leave()
                }
            } failure: { params in
                print("视频获取失败")
                error = "视频获取失败"
                group.leave()
            }
        } else {
            for image in images {
                group.enter()
                MMYGNetwork<MYGCommonAPI, MYGEmptyModel>.request(target: .uploadOssFiles(image: image)) { _ in
                    
                } stringBlock: { text in
                    urls.append(text)
                    group.leave()
                } failed: { _, err in
                    error = err
                    group.leave()
                }
            }
        }
        
        group.notify(queue: DispatchQueue.main) {
            if let error = error {
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
                return
            }
            
            MYGNetwork<MYGRegisterAPI, MYGEmptyModel>.request(target: .add(content: text, type: self.videos==nil ? 1 : 2, medias: urls, address: address, lng: "\(lng)", lat: "\(lat)", range: range)) { _ in
                MYGLoading.hide()
                NotificationCenter.default.post(name: NSNotification.Name.init("reloadDyTable"), object: nil)
                MMYGHUD.showToast(text: "发布成功") {[weak self] in
                    self?.navigationController?.popViewController()
                }
                
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
        }
    }
}
